package com.zhenyi.liuxue.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.cjw.model.DBMap;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.liuxue.common.model.LxCompany;
import com.liuxue.common.model.LxPolicy;
import com.liuxue.common.model.LxRange;
import com.liuxue.common.model.LxSchool;
import com.liuxue.common.model.LxUkSchool;
import com.liuxue.common.model.LxUser;
import com.zhenyi.liuxue.core.TemplateUtils;

import cn.hutool.core.date.DateUtil;

public class PolicyController extends AdminController {

	public void list() {
		Long ukSchoolId = getParaToLong("ukSchoolId");
		String keyword = getPara("keyword");
		if (ukSchoolId == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxUkSchool ukSchool = LxUkSchool.dao.findById(ukSchoolId);
		if (ukSchool == null) {
			renderFailure(404, "not found");
			return;
		}
		Kv kv = Kv.create();
		kv.set("unionSchoolId", ukSchool.getUnionSchoolId());
		if (StrKit.notBlank(keyword)) {
			kv.set("keyword", keyword);
			setAttr("keyword", keyword);
		}
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindPolicy", kv);
		Page<LxPolicy> pages = LxPolicy.dao.paginate(getPage(), getPageSize(), sqlPara);

		setAttr("schoolId", LxSchool.dao.searchFirst("unionSchoolId", ukSchool.getUnionSchoolId()).getId());
		setAttr("ukSchoolId", ukSchoolId);
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		render("/lx/admin/ukSchools/policyList.html");
	}

	/**
	 * 推送最新政策
	 */
	public void send() {
		Long policyId = getParaToLong("policyId");
		if (policyId == null) {
			renderFailure();
			return;
		}
		LxPolicy policy = LxPolicy.dao.findById(policyId);
		if (policy == null) {
			renderFailure();
			return;
		}
		Long schoolId = policy.getSchoolId();
		if (schoolId == null) {
			renderFailure();
			return;
		}
		LxSchool school = LxSchool.dao.findById(schoolId);
		if (school == null) {
			renderFailure();
			return;
		}
		// String openId = getPara("openId");

		Kv kv = Kv.by("schoolId", schoolId);
		// SqlPara sqlPara = lxDb.getSqlPara("LXFindSubscribeSchoolUsers", kv);
		// SqlPara sqlPara = lxDb.getSqlPara("LXFindSubscribeSchoolAllUsers",
		// kv);
		SqlPara sqlPara = db.getSqlPara("LXAdminFindOpenIdUser", kv);
		List<LxUser> users = LxUser.dao.find(sqlPara);
		TemplateUtils templateUtils = new TemplateUtils();
		String[] openIds = getParaValues("openId");
		if (openIds != null) {
			for (String openId : openIds) {
				templateUtils.send(openId, "亲爱的用户，您订阅的大学有最新通知", school.getName(), policy.getTitle(), DateUtil.today(),
						"点击查看详细信息", "/pages/app/schools/policyInfo/policyInfo?policyId=" + policyId);
			}
		} else {
			for (LxUser lxUser : users) {
				templateUtils.send(lxUser.getOpenId(), "亲爱的用户，您订阅的大学有最新通知", school.getName(), policy.getTitle(),
						DateUtil.today(), "点击查看详细信息", "/pages/app/schools/policyInfo/policyInfo?policyId=" + policyId);
			}
			policy.setPushTime(new Date());
			policy.update();
		}
		// templateUtils.send("o0OpG4xcUD-h3xKr_6NCF4DAJQM8",
		// "亲爱的用户，您订阅的大学有最新通知", "布里斯托大学", "布里斯托大学2019年语言课申请现已开放",
		// "2018年12月19日", "点击查看详细信息",
		// "/pages/app/schools/policyInfo/policyInfo?policyId=97");
		renderSuccess();

	}

	public void info() {
		setReferer();
		Long id = getParaToLong("id");
		Long schoolId = getParaToLong("schoolId");
		if (id != null) {
			LxPolicy info = LxPolicy.dao.findById(id);
			if (info == null) {
				renderFailure(404, "not found");
				return;
			}

			if (info.getRangeType().equals(2)) {
				Kv kv = Kv.create();
				kv.set("policyId", id);
				SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
				List<LxRange> rangeList = LxRange.dao.find(sqlPara);
				ArrayList<DBMap> locationLimit = new ArrayList<>();
				for (LxRange range : rangeList) {
					DBMap map = new DBMap();
					map.put("province", range.getProvince());
					map.put("city", range.getCity());
					locationLimit.add(map);
				}
				info.put("locationLimit", locationLimit);

			} else if (info.getRangeType().equals(3)) {
				Kv kv = Kv.create();
				kv.set("policyId", id);
				SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
				List<LxRange> rangeList = LxRange.dao.find(sqlPara);
				ArrayList<DBMap> companyLimit = new ArrayList<>();
				ArrayList<DBMap> locationLimit = new ArrayList<>();
				for (LxRange range : rangeList) {
					if (range.getCompanyId() != null) {
						DBMap map = new DBMap();
						map.put("id", range.getCompanyId());
						map.put("name", range.get("companyName"));
						companyLimit.add(map);
					}
					if (range.getLocation() != null) {
						String[] locationList = range.getLocation().split(",");
						DBMap map = new DBMap();
						map.put("province", locationList[0]);
						map.put("city", locationList.length > 1 ? locationList[1] : "");
						locationLimit.add(map);
					}
				}
				info.put("companyLimit", companyLimit);
				info.put("locationLimit", locationLimit);
			}
			setInfoItem(JsonKit.toJson(info));
		}
		SqlPara sqlPara2 = Db.use("liuxue").getSqlPara("LXFindCompanies");
		List<LxCompany> companies = LxCompany.dao.find(sqlPara2);
		setAttr("schoolId", schoolId);
		setAttr("companies", JsonKit.toJson(companies));
		render("/lx/admin/ukSchools/policyInfo.html");
	}

	public void submit() {
		Long id = getParaToLong("id");
		Long schoolId = getParaToLong("schoolId");
		String cover = getPara("cover");
		String title = getPara("title");
		String subtitle = getPara("subtitle");
		String content = getPara("content");
		String attach = getPara("attach");
		Long sort = getParaToLong("sort", 99999L);
		Integer status = getParaToInt("status", 1);
		Integer rangeType = getParaToInt("rangeType");
		String companyLimit = getPara("companyLimit");
		String locationLimit = getPara("locationLimit");

		boolean isNew = id == null;
		LxPolicy info = isNew ? new LxPolicy() : LxPolicy.dao.findById(id);
		if (!isNew && info == null) {
			renderFailure(404, "not found");
			return;
		}
		if (isNew) {
			info.setAddTime();
		}
		info.setSchoolId(schoolId);
		info.setCover(cover);
		info.setTitle(title);
		info.setSubtitle(subtitle);
		info.setContent(content);
		info.setAttach(attach);
		info.setSort(sort);
		info.setStatus(status);
		info.setEditTime(new Date());
		info.setRangeType(rangeType);
		boolean flag = isNew ? info.save() : info.update();
		if (flag) {
			// 处理可见范围
			Kv kv = Kv.create();
			if (id != null) {
				kv.set("policyId", info.getId());
				SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
				List<LxRange> rangeList = LxRange.dao.find(sqlPara);
				for (LxRange range : rangeList) {
					range.delete();
				}
			}
			if ((rangeType.equals(2) || rangeType.equals(3)) && StrKit.notBlank(locationLimit)) {
				String[] locations = locationLimit.split(";");
				for (String loc : locations) {
					kv.set("policyId", info.getId());
					kv.set("location", loc);
					SqlPara sp = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
					LxRange range = LxRange.dao.findFirst(sp);
					if (range == null) {
						range = new LxRange();
						range.setPolicyId(info.getId());
						range.setLocation(loc);
						String[] provinceCity = loc.split(",");
						range.setProvince(provinceCity[0]);
						if (provinceCity.length > 1) {
							range.setCity(provinceCity[1]);
						} else {
							range.setCity("");
						}
						range.save();
					}
				}
			}
			if (rangeType.equals(3) && StrKit.notBlank(companyLimit)) {
				String[] idStrs = companyLimit.split(";");
				for (String idStr : idStrs) {
					kv.set("policyId", info.getId());
					kv.set("companyId", idStr);
					SqlPara sp = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
					LxRange range = LxRange.dao.findFirst(sp);
					if (range == null) {
						range = new LxRange();
						range.setPolicyId(info.getId());
						range.setCompanyId(Long.valueOf(idStr));
						range.save();
					}
				}
			}
		}
		renderFlag(flag);
	}

	public void delete() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxPolicy info = LxPolicy.dao.findById(id);
		if (info == null) {
			renderFailure(404, "not found");
			return;
		}
		renderFlag(info.delete());
	}

}
